package py.com.fms.prd.session.maintenances;

//External classes imports 
//Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.drools.rule.Collect;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports

// BEANS
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.prd.bean.SuppliesBean;

// SERVICES
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.prd.persistence.services.SuppliesServices;
import py.com.fms.prd.persistence.services.SuppliesTypeServices;

// OTHERS
import py.com.fms.exception.CommonException;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;

@SuppressWarnings("unused")
@Name("editSupplies")
@Scope(ScopeType.SESSION)
public class EditSupplies {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private DateAssistant dateAssist;
	
	// Beans
	private UsersBean user = null; // For User Data 
	private SuppliesBean supplies = null; // Used in main forms
	private SuppliesBean editSupplies = null; // Used for update operations

	// Services
	private UsersServices usSrv;
	private SuppliesServices spSrv;
		
	// Collections
	private Collection<SuppliesBean> allSupplies; // Used to store all object data

	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 */

	// Used to initialize Objects
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) { // Checking initialization Flag
			this.initBeans(); // Initializing Beans
			this.initServices(); // Initializing Services
			this.initAssistants(); // Initializing Assistants
			this.initCollections(); // Initializing Collections
			this.loadDataGrid(); // Loading data for grid
			this.loadUserData(); // Retrieving User Data
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	
    private void initBeans(){
    	
	  	if(user == null){
	  		user = new UsersBean();
	  	}
	  	
	  	if(supplies == null){
	  		supplies = new SuppliesBean();
	  		supplies.setStatus(true);
	  		supplies.setOperateStock(false);
	  	}
	  	
	  	if(editSupplies == null){
	  		editSupplies = new SuppliesBean();
	  	}
	  	
	
    }
    
    private void initServices() throws CommonException{
    	
    	if (spSrv == null){
			spSrv = new SuppliesServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
    	
    }
    
    private void initAssistants(){
    	
    	if(aid == null){
    		aid = new WithinHolder();
    	}
    	
    	if(convert == null){
			convert = new ConvertAssistant();
		}
    	
    	if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
    	
    }
    
    private void initCollections(){
    	
    	if(allSupplies == null){
    		allSupplies = new ArrayList<SuppliesBean>();
    	}
    }
    
    // Used to clean all objects
    public void cleanData() throws CommonException{
    	
    	// Cleaning Beans
  		user = null;
  		supplies = null;
  		editSupplies = null;
        
  		// Cleaning Services
		spSrv = null;
		usSrv = null;
        
		// Cleaning Assistants
		aid = null;
		convert = null;
		dateAssist = null;
		
		// Cleaning Collections
		allSupplies = null;
    	
    }
    
    private void loadUserData() throws CommonException{
    	
    	if(credentials != null){ // Checking if credentials are null
			System.out.println("Credenciales Encontradas");
			
			this.getUser().setUserName(credentials.getUsername()); // Retrieving user name
			System.out.println("User Name: " + this.getUser().getUserName());
			
			user = usSrv.getUserDataByName(this.getUser().getUserName()); // Retrieving user Data
			this.setUser(user);
			System.out.println("User: " + this.getUser());
			
		}else{	
			System.out.println("Credenciales Nulas");
		}
    }
    
 // Used to load a grid using a collection
	private void loadDataGrid() throws CommonException {
		if (spSrv.getContSuppliesById(this.supplies.getId()) > 0 ) {
			try {
				this.setAllSupplies(spSrv.getAllSupplies());
				for (SuppliesBean supplies : this.getAllSupplies()) {
					System.out.println(supplies.getCod() + " - " + supplies.getDescrip());
				}
			} catch (CommonException e) {
				e.printStackTrace();
			}
		}
	}

	// Used to cancel
	public void cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.cleanData();
		this.setInitVar("S");
	}

		

	// Used for data saving process
	public void saveNewData() throws ParseException, CommonException {
		try {
//			this.facesMessages.clear();
			SuppliesBean newSupplies = new SuppliesBean(); // Instantiating a object for saving


			if (this.getSupplies() == null) {
				System.out.println("this.getBurden() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("Before setNewCurrency");
			// Setting field values
			newSupplies.setCod(this.convert.convertField(this.getSupplies().getCod()));
			newSupplies.setDescrip(this.convert.convertField(this.getSupplies().getDescrip()));
			if(this.getSupplies().getBurdenData() != null){
				newSupplies.setIdBurden(this.getSupplies().getBurdenData().getId());
			}else{
				newSupplies.setIdBurden(null);
			}
			if(this.getSupplies().getFamilyData() != null){
				newSupplies.setIdFamily(this.getSupplies().getFamilyData().getId());
			}else{
				newSupplies.setIdFamily(null);
			}
			if(this.getSupplies().getGroupData() != null){
				newSupplies.setIdGroup(this.getSupplies().getGroupData().getId());
			}else{
				newSupplies.setIdGroup(null);
			}
			
			newSupplies.setIdEnt(user.getIdEnt());
			newSupplies.setIdSupplier(this.getSupplies().getSupplierData().getId());
			newSupplies.setIdSuppliesType(this.getSupplies().getSuppliesTypeData().getId());
			newSupplies.setLastCost(new BigDecimal(0));
			newSupplies.setTax(this.getSupplies().getTaxData().getId());
			newSupplies.setStatus(this.getSupplies().getStatus());
			newSupplies.setStartDate(DateAssistant.getHoleDateTime());
			newSupplies.setOperateStock(this.getSupplies().getOperateStock());
			System.out.println(DateAssistant.getHoleDateTime());
			newSupplies.setUserIns(user.getId());

			spSrv.saveNewSupplies(newSupplies);
			
			
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			
			this.cleanData(); // Cleaning Objects
			this.setInitVar("S"); // Setting initialization Flag
			
		}

	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id){
		System.out.println("id = " + id.toString());
		for (SuppliesBean bean : this.getAllSupplies()) {
			if(bean.getId().equals(id)){
				this.setEditSupplies(bean);
				return;
			}			
		}	
	}
	
	// Updating Data in Database
	public void dataToEditUpd() throws ParseException{
		try {

			spSrv.updateSupplies(this.getEditSupplies());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	// Deleting Data from Database
	public void dataToDelete(Long id){
		for (SuppliesBean bean: this.getAllSupplies()){
			if (bean.getId().equals(id)) {
				try {
					spSrv.deleteSuppliesById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}

	
	// MUTATORS AND ACCESORS
	
	public FacesMessages getFacesMessages() {
		return facesMessages;
	}


	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}


	public Log getLog() {
		return log;
	}


	public void setLog(Log log) {
		this.log = log;
	}


	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}


	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}


	public String getInitVar() {
		return initVar;
	}


	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}


	public UsersBean getUser() {
		return user;
	}


	public void setUser(UsersBean user) {
		this.user = user;
	}


	public SuppliesBean getSupplies() {
		return supplies;
	}


	public void setSupplies(SuppliesBean supplies) {
		this.supplies = supplies;
	}


	public SuppliesBean getEditSupplies() {
		return editSupplies;
	}


	public void setEditSupplies(SuppliesBean editSupplies) {
		this.editSupplies = editSupplies;
	}


	public Collection<SuppliesBean> getAllSupplies() {
		return allSupplies;
	}


	public void setAllSupplies(Collection<SuppliesBean> allSupplies) {
		this.allSupplies = allSupplies;
	}

	
	
}
